package org.zjx.analysis.inventor;

import lombok.Getter;
import lombok.SneakyThrows;
import org.zjx.util.ImageUtil;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;

@Getter
public class PropAnalysis {
    public static final int CELL_SIZE = 50;

    private final BufferedImage screenshot;

    private final int width;
    private final int height;

    public PropAnalysis(BufferedImage bufferedImage) {
        this.screenshot = bufferedImage;
        width = latticeNumber(bufferedImage.getWidth());
        height = latticeNumber(bufferedImage.getHeight());
    }

    public List<BufferedImage> getItemImages() {
        List<BufferedImage> bufferedImages = new ArrayList<>(width * height);
        for (int i = 0; i < width * height; i++)  {
            bufferedImages.add(ImageUtil.cutImage(screenshot,getIndexArea(i)));
        }
        return bufferedImages;
    }

    public Rectangle getIndexArea(int index) {
        // 计算行列位置
        int row = index / width;
        int col = index % width;

        // 计算格子实际位置（考虑1像素间隔）
        int totalCellSize = CELL_SIZE + 1;
        int x = col * totalCellSize;
        int y = row * totalCellSize;

        // 返回格子区域（最后一个格子可能不需要+1像素间隔）
        boolean isLastCol = (col == width - 1);
        boolean isLastRow = (row == height - 1);

        int cutWidth = isLastCol ? CELL_SIZE : totalCellSize;
        int rectHeight = isLastRow ? CELL_SIZE : totalCellSize;

        return new Rectangle(x, y, cutWidth + 1, rectHeight + 1);
    }

    /**
     * 计算单维度（宽度或高度）上的格子数量
     *
     * @param len 图片宽度或高度（像素）
     * @return 该维度上的格子数量
     */
    @SneakyThrows
    private int latticeNumber(int len) {
        if (len < CELL_SIZE + 2)
            throw new IllegalArgumentException("提供的道具栏区域格子小于单个格子" + CELL_SIZE + "像素！！！");
        return (len - 1) / (CELL_SIZE + 1);
    }

}
